<?php
namespace app\system\controller;

use app\common\model\ConfigGroupModel;
use app\common\model\ConfigModel;
use think\Request;

class ConfigController extends BaseController
{

    private $configModel;
    private $configGroupModel;

    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->configModel      = new ConfigModel();
        $this->configGroupModel = new ConfigGroupModel();
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->param('config/a');
            if ($this->configModel->batchSave($data)) {
                $this->configModel->updateCache();
                $this->success('操作成功！', url('index'));
            } else {
                $this->error($this->configModel->getError());
            }
        }
        $config = $this->configModel->getConfig($this->getUid());
        $this->assign('config', $config);
        $content = $this->fetch();
        return $this->display($content);
    }

    /**
     * 更新缓存
     */
    public function updateCache()
    {
        $this->configModel->updateCache();
        $this->success('操作成功！', url('index'));
    }

    /**
     * 添加配置
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $data   = $this->request->param();
            $data['site_id'] = $this->getSiteId();
            $result = $this->validate($data, 'ConfigValidate.add');
            if ($result !== true) {
                $this->error($result);
            }
            if ($this->configModel->addData($data)) {
                $this->configModel->updateCache();
                $this->success('添加成功！', url('index'));
            } else {
                $this->error($this->configModel->getError());
            }
        }
        $group = $this->configGroupModel->order("group_sort")->select();
        $this->assign('group', $group);
        return $this->fetch();
    }

    /**
     * 删除配置
     */
    public function del()
    {
        $id = $this->request->param('id/d', 0);
        if ($this->configModel->delData($id)) {
            $this->configModel->updateCache();
            $this->success('删除成功！');
        }
    }
}
